#!/usr/bin/python
# -*- coding: UTF-8 -*-

import logging
import random

from tbitem.util.postDiscuz import postDiscuzBBs

server_logger = logging.getLogger("server")
import time
from BaseWeb import models as BaseWeb_models
from tbitem.util import maokoulingClass

from tbitem.util.itemTemplate import ContentFactory_forDiscuz, ContentFactory_forDjango
from tbitem.util.qiboPOST import bokeePOST, ContentConfig
import os,django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "shareAPI2020TB.settings")# project_name 项目名称
django.setup()

import json
import jsonpath
import requests

from tbitem import models
def getATitle():
    #从数据库中取出淘宝已经处理过爬取的链接
    run_modelQuery = models.RunModel.objects.first()
    # print(run_modelQuery.modelType)
    if run_modelQuery.modelType == 0:
        querySetList = models.BBSContent.objects.filter(status=2).all()
        print(querySetList)
    elif run_modelQuery.modelType == 1:
        querySetList = models.DIYTitle.objects.filter(status=2).all()
    else:
        querySetList = models.BBSContent.objects.filter(status=2).all()
        print(querySetList)

    return querySetList


'''先循环用户，每个用户调用5次
需要的参数：
pid (淘宝pid from DiscuzAccount表)
apkey (喵口令 from DiscuzAccount表))
fid ('57'  # 板块编号  DiscuzAccount表)
username ('怎么样评测'  # 发帖用户名from DiscuzAccount表)


'''
def step5():
    print(models.BBSContent.objects.all())
    print('3333333333333333333333333333333333')

    server_logger.error(f"step5-----Start")
    # try:
    # 调用数据库账号设置：
    DiscuzAccount_QuerySetList = models.DiscuzAccount.objects.all()
    print(DiscuzAccount_QuerySetList)
    if not DiscuzAccount_QuerySetList:
        print('step5-----step5企博账号还没有配置呢，请速速配置---')
        server_logger.error(f"step5-----step5企博账号还没有配置呢，请速速配置----")
        return
    else:

        for discuz_Account in DiscuzAccount_QuerySetList:
            server_logger.error(f"step5-----运行账号：{discuz_Account.username}----")

            querySetList = getATitle()  #获取有效的数据集合
            # print(querySet.keyword)  #关键词
            # print(querySet.tbid)  # 淘宝id  ->取商品图文，取tbkurl
            # print(querySet.contentWord)  #句子
            if len(querySetList)==0:
                print("step5-----运行账号：没有发帖资源了----")
                server_logger.error(f"step5-----运行账号：没有发帖资源了----")
            for querySet in querySetList[0:discuz_Account.sendNum]:   #循环次数根据DiscuzAccount数据表的设定
                print(querySet)
                # 尝试取淘宝客推广链接


                TbIndex_Query = models.TbIndex.objects.filter(tbid=querySet.tbid).first()


                #个人用的话可以省miaokouling的api次数，但是多账号的话，会影响taobaoke的收益归属
                # if not TbIndex_Query.tbkURL:  # 如果没有链接，就开始申请淘宝客链接
                #     logging.info("没有淘宝客链接，转换链接（店铺，item两个都要）")
                #
                #     # id转链接
                #     abc = maokoulingClass.maokouling_ONE()
                #     abc.pid = bokeeAccount.pid
                #     abc.apkey = bokeeAccount.apkey
                #     abc.itemid = TbIndex_Query.tbid
                #     abc.userid = maokoulingClass.item_to_SELLID(abc)
                #     tbkUrl = maokoulingClass.tblink_get_gaoyong(abc)
                #     tbShopUrl = maokoulingClass.userid_to_shopTBK_link(abc)
                #
                #     # 链接入库
                #     TbIndex_Query.tbkURL = tbkUrl
                #     TbIndex_Query.tbkShopURL = tbShopUrl
                #     TbIndex_Query.save()

                logging.info("以下代码目的：转换taobaoke链接）")

                # id转链接
                abc = maokoulingClass.maokouling_ONE()
                abc.pid = discuz_Account.pid
                abc.apkey = discuz_Account.apkey
                print(type(querySet.tbid))
                abc.itemid = querySet.tbid
                abc.tbname = discuz_Account.tbusername
                abc.userid = maokoulingClass.item_to_SELLID(abc)
                print(abc)
                tbkUrl = maokoulingClass.tblink_get_gaoyong(abc)
                tbShopUrl = maokoulingClass.userid_to_shopTBK_link(abc)

                # 链接入库，因为多账号，不知道是谁的淘宝客链接，所以不保存淘宝客链接了，等到api查询量不够的时候在修改吧
                TbIndex_Query.tbkURL = tbkUrl
                TbIndex_Query.tbkShopURL = tbShopUrl
                TbIndex_Query.save()

                # 生成发帖模板
                # 根据这次的id查找对应的图片合集和评论合集
                TBimg_Query = models.TbIMG.objects.filter(tbimg_Index=TbIndex_Query).all()
                TBComment_Query = models.TbComment.objects.filter(tbComment_Index=TbIndex_Query).all()

                #获取数据库中的前缀词和后缀词
                firstWord_Query = models.TbFirstWord.objects.order_by('?')[:1].first()  # @type:querySet
                lastWord_Query = models.TbLastWord.objects.order_by('?')[:1].first()   # @type:querySet



                if not firstWord_Query:
                    firstWord = '买前必看！'
                else:
                    firstWord = firstWord_Query.firstWord
                if not lastWord_Query:
                    lastWord = '质量怎么样？'
                else:
                    lastWord = lastWord_Query.lastWord


                """
                TbIndex_Query 实例   tbindex， /商品淘链接/店铺淘链接
                querySet    实例  BBSContent       /关键词/源标题/
                TBimg_Query  实例(多)  TbIMG       /商品的图片合集
                TBComment_Query  实例(多)  TbComment  商品的评论合集
                """
                print(TbIndex_Query)
                print(querySet)
                print(TBimg_Query)
                print(TBComment_Query)
                '''-------------------------------------------'''
                '''------------数据库内容合成文章的内容部分（）---------------'''
                '''-------------------------------------------'''
                # 组合成文章 htmlContent
                htmlContent,htmlpinglunList = ContentFactory_forDiscuz(TbIndex_Query, querySet, TBimg_Query, TBComment_Query)
                print(htmlContent)




                '''本次帖子存储部分（扩展可删除）'''

                htmlContentFromDjango, htmlpinglunListFromDjango = ContentFactory_forDjango(TbIndex_Query, querySet, TBimg_Query,
                                                                        TBComment_Query)
                # 随机获得作者，数据表有绑定获得由pid和喵口令id，用来发帖
                querySetAuthorList = BaseWeb_models.Author.objects.all()
                if not querySetAuthorList:
                    # return HttpResponse('没有作者账号了')
                    print('没有作者账号了')
                querySetAuthor = random.choice(querySetAuthorList)
                DetailPageQuerySet = BaseWeb_models.DetailPage.objects.create(
                    tbid=querySet.tbid,
                    detail_auther=querySetAuthor,
                    title=querySet.contentLink.title,
                    content=htmlContentFromDjango,
                    tags='',
                    detail_WebFid_id=1)
                DetailPageQuerySet.save()
                for commentItem in htmlpinglunListFromDjango:
                    querySetAuthorRandom = random.choice(querySetAuthorList)  # 随机获得发帖作者
                    CommentQuerySet = BaseWeb_models.Comment.objects.create(
                        comment_auther=querySetAuthorRandom,
                        comment_detailpage=DetailPageQuerySet,
                        comment_content=commentItem,
                        likeNum=1
                    )
                    CommentQuerySet.save()
                '''本次帖子存储部分（扩展可删除--end）'''



                '''-------------------------------------------'''
                '''------------文章发布---------------'''
                '''-------------------------------------------'''

                # 发布内容如果发布成功，就更改tbindex表的状态为3
                if htmlContent == None:
                    logging.info("组合文章出错")
                    server_logger.error(f"step5-----组合文章出错")
                else:
                    # 发布discuz
                    # '''3、发博客'''
                    # # 调用企业博客发帖模块函数块需要的内容----START

                    #获取帖子的标题
                    subject = '初始化标题'

                    firstWord_Query = models.TbFirstWord.objects.order_by('?')[:1].first()  # @type:querySet
                    lastWord_Query = models.TbLastWord.objects.order_by('?')[:1].first()  # @type:querySet
                    if not firstWord_Query:
                        firstWord = ''
                    else:
                        firstWord = firstWord_Query.firstWord
                    if not lastWord_Query:
                        lastWord = ''
                    else:
                        lastWord = lastWord_Query.lastWord


                    run_modelQuery = models.RunModel.objects.first()
                    if run_modelQuery.modelType == 0:
                        subject = f'{firstWord}{querySet.contentLink.title}{lastWord}',
                    elif run_modelQuery.modelType == 1:
                        subject = f"{firstWord}{querySet.title}{lastWord}",
                    else:
                        subject = f'{firstWord}{querySet.contentLink.title}{lastWord}',
                    subject = subject[0]


                    '''#发帖信息初始化'''
                    # subject = htmlContent  # 标题
                    message = htmlContent  # 内容
                    fid = discuz_Account.fid  # 板块编号
                    username = discuz_Account.username  # 发帖用户名
                    url = discuz_Account.postUrl  #发帖地址
                    pinglunList = htmlpinglunList  # 评论楼层

                    # 格式化评论楼层
                    for i in pinglunList:
                        message = f'{message}|||{i}'


                    #开始发帖
                    postresult = postDiscuzBBs(subject, message, fid, username,url)


                    if postresult == True:
                        print(f"{discuz_Account.discuzName}发帖成功")
                        # 发帖成功
                        # # 调用discuz发帖模块函数块需要的内容----END
                        querySet.status = 3
                        querySet.save()
                        time.sleep(50)
                        # cursor.execute(f'update JiSuBBS set 备用 = 3,生成评论内容 = {content}')
                    else:
                        server_logger.error("")
                        server_logger.error(f"step5-----帖子数量发够了，请检查----")
                        break
                        # exit(code='帖子数量发够了,退出程序')
                    server_logger.error(f"step5-----发布discuz成功")
                    time.sleep(5)

    # except Exception as e:
    #     print('344')
    #     print(e)
    #     server_logger.error(f"step5-----step5发布discuz出错----{e}")
if __name__ == '__main__':
    step5()  #取出一条 状态2的bbscontent数据，然后发企博,发布成功，设置 BBSContent 表状态为3（已成功发布）



